package l1j.server.server.command.executor;

import java.util.ArrayList;
import java.util.Iterator;

import l1j.opqlo.Server.L1World.L1World;
import l1j.server.Config;
import l1j.server.server.datatables.ItemTable;
import l1j.server.server.model.Getback;
import l1j.server.server.model.L1Inventory;
import l1j.server.server.model.L1Object;
import l1j.server.server.model.L1Teleport;
import l1j.server.server.model.Instance.L1ItemInstance;
import l1j.server.server.model.Instance.L1PcInstance;
import l1j.server.server.serverpackets.S_CharVisualUpdate;
import l1j.server.server.serverpackets.S_MapID;
import l1j.server.server.serverpackets.S_OtherCharPacks;
import l1j.server.server.serverpackets.S_OwnCharPack;
import l1j.server.server.serverpackets.S_RemoveObject;
import l1j.server.server.serverpackets.S_SystemMessage;
import l1j.server.server.serverpackets.S_Weather;

public class L1DieFight implements L1CommandExecutor {
	
	public static L1CommandExecutor getInstance() {
		return new L1DieFight();
	}
	private L1DieFight() {
	}
	// @Override
	@Override
	public void execute(L1PcInstance pc, String cmdName, String arg) {
		if (arg.equalsIgnoreCase("開始")) {
			final int[]loc = {pc.getX() , pc.getY() , pc.getMapId() };
			Config.活動座標 =loc;
			L1World.getInstance().broadcastPacketToAll(new S_SystemMessage("\\aG【死鬥】活動已開啟。"));
			L1World.getInstance().broadcastPacketToAll(new S_SystemMessage("\\aJ輸入指令【 .參加活動】進入【死鬥】活動地圖。"));
		}else if(arg.equalsIgnoreCase("GO")){
			L1World.getInstance().broadcastPacketToAll(new S_SystemMessage("\\aG【死鬥】活動開始進行，現在開始停止入場。"));
			final int[]loc = {0 , 0 ,0 };
			Config.活動座標 =loc;
			final Iterator<L1Object> ite = L1World.getInstance().getAllVisibleObjectsMap(pc , true).iterator();
			while(ite.hasNext()){
				final L1PcInstance tpc = (L1PcInstance) ite.next();
				if(!tpc.isGm()){
					tpc._inFighting = 2;
					L1Teleport.randomTeleport(tpc, false);
				}
			}
		}else if(arg.equalsIgnoreCase("STOP")){
			ArrayList<L1Object>_pclist = L1World.getInstance().getAllVisibleObjectsMap(pc , true);
			Iterator<L1Object> ite = _pclist.iterator();
			ArrayList<L1PcInstance>winner = new ArrayList<L1PcInstance>();
			while(ite.hasNext()){
				final L1PcInstance tpc = (L1PcInstance) ite.next();
				if(tpc.isGm()){
					continue;
				}
				if(!createNewItem1(tpc ,Config.活動參加獎[0],Config.活動參加獎[1])){
					pc.sendPackets(new S_SystemMessage(tpc.getName()+" 背包已滿未領取到參加獎。"));
				}
				if(tpc._inFighting ==3){
					continue;
				}
				tpc._inFighting = 3;

				if(tpc.isDead()){
					reStartPlayer(tpc);
					continue;
				}
				winner.add(tpc);
			}
			Config.活動參加獎[0] =0;
			Config.活動參加獎[1] =0;
			
			final StringBuilder msg = new StringBuilder().append("本次獲勝的是: ");
			for(L1PcInstance winpc : winner){
				msg.append(winpc.getName()).append(" ");
				if(!createNewItem2(winpc ,Config.活動獎品[0],Config.活動獎品[1])){
					pc.sendPackets(new S_SystemMessage(winpc.getName()+" 背包已滿未領取到優勝獎品。"));
				}
			}
			Config.活動獎品[0] =0;
			Config.活動獎品[1] =0;
			msg.append("。");
			L1World.getInstance().broadcastPacketToAll(new S_SystemMessage("\\aG【死鬥活動】:"+msg.toString()));
			winner.clear();
			_pclist.clear();
//			_pclist = L1World.getInstance().getAllVisibleObjectsMap(pc , true);
//			ite = _pclist.iterator();
//			ArrayList<S_ChatPacket>splist = new ArrayList<S_ChatPacket>();
//			while(ite.hasNext()){
//				final L1PcInstance tpc = (L1PcInstance) ite.next();
//				if(!tpc.isGm()){
//					splist.add(new S_ChatPacket(tpc, msg.toString() ,35, 0));
//				}
//			}
			msg.delete(0, msg.length());
//			_pclist.clear();
//			_pclist = L1World.getInstance().getAllVisibleObjectsMap(pc , true);
//			ite = _pclist.iterator();
//			while(ite.hasNext()){
//				final L1PcInstance tpc = (L1PcInstance) ite.next();
//				for(final S_ChatPacket sp : splist){
//					tpc.sendPackets(sp);
//				}
//			}
//			_pclist.clear();
		}else if(arg.equalsIgnoreCase("結束")){
			final Iterator<L1Object> ite =L1World.getInstance().getAllVisibleObjectsMap(pc , true).iterator();
			while(ite.hasNext()){
				final L1PcInstance tpc = (L1PcInstance) ite.next();
				tpc._inFighting = 0;
					L1Teleport.teleport(tpc, 32810 ,  32833 , (short)1784 , 0 ,false);	
			}
			final int[]loc = {0 , 0 ,0 };
			Config.活動座標 =loc;
			L1World.getInstance().broadcastPacketToAll(new S_SystemMessage("\\aG【死鬥】活動已關閉，謝謝各位參加。"));
		} else {
			pc.sendPackets(new S_SystemMessage("請輸入: ."+cmdName + " 開始、結束 、GO、STOP。"));
		}
	}
	// 副本內死亡的玩家重新開始
	private void reStartPlayer(final L1PcInstance pc) {
		pc.stopPcDeleteTimer();

		final int[] loc = Getback.GetBack_Location(pc, true);

		pc.removeAllKnownObjects();
		pc.broadcastPacketAll(new S_RemoveObject(pc));

		pc.setCurrentHp(pc.getLevel());
		pc.set_food(40);
		pc.setDead(false);
		pc.setStatus(0);
		L1World.getInstance().moveVisibleObject(pc, loc[2]);
		pc.setX(loc[0]);
		pc.setY(loc[1]);
		pc.setMap((short) loc[2]);
		pc.sendPackets(new S_MapID(pc.getMapId(), pc.getMap().isUnderwater()));
		pc.broadcastPacketAll(new S_OtherCharPacks(pc));
		pc.sendPackets(new S_OwnCharPack(pc));
		pc.sendPackets(new S_CharVisualUpdate(pc));
		pc.startHpRegeneration();
		pc.startMpRegeneration();
		pc.sendPackets(new S_Weather(L1World.getInstance().getWeather()));
		if (pc.getHellTime() > 0) {
			pc.beginHell();
		}
	}
	private boolean createNewItem1(L1PcInstance pc,final int item_id,final int count) {
		L1ItemInstance item = ItemTable.getInstance().createItem(item_id);
		if (item != null) {
			item.setCount(count);
			if (pc.getInventory().checkAddItem(item, count) == L1Inventory.OK) {
				pc.getInventory().storeItem(item);
				pc.sendPackets(new S_SystemMessage("獲得參加獎勵: "+item.getLogName())); // %0を手に入れました。
				return true;
			} else { // 持てない場合は地面に落とす 處理のキャンセルはしない（不正防止）
				//L1World.getInstance().getInventory(pc.getX(), pc.getY(), pc.getMapId()).storeItem(item);
				return false;
			}
		} else {
			return false;
		}
	}
	private boolean createNewItem2(L1PcInstance pc,final int item_id,final int count) {
		L1ItemInstance item = ItemTable.getInstance().createItem(item_id);
		if (item != null) {
			item.setCount(count);
			if (pc.getInventory().checkAddItem(item, count) == L1Inventory.OK) {
				pc.getInventory().storeItem(item);
				pc.sendPackets(new S_SystemMessage("獲得優勝獎勵: "+item.getLogName())); // %0を手に入れました。
				return true;
			} else { // 持てない場合は地面に落とす 處理のキャンセルはしない（不正防止）
				//L1World.getInstance().getInventory(pc.getX(), pc.getY(), pc.getMapId()).storeItem(item);
				return false;
			}
		} else {
			return false;
		}
	}
}
